//
//  CZSendStatusController.swift
//  GZWeibo007
//
//  Created by newuser on 15/12/27.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

import SVProgressHUD

class CZSendStatusController: UIViewController{

    
    //toolbar顶部约束
    private var toolBarBottomCon:NSLayoutConstraint?
    
    /// 微博最大的长度
    private let maxTipLength = 25
    
    /// 照片选择器的view的底部约束
    private var photoSelectorViewBottomCon: NSLayoutConstraint?
    
    func close() {
        
        //将键盘退出去
        //        textView.endEditing(true)
        //取消第一响应者
        SVProgressHUD.dismiss()
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func send() {
        
        let text = textView.emoticonText()
        //获取照片
        let image = photoSelectorVC.photos.first
        
        if maxTipLength - text.characters.count < 0 {
          SVProgressHUD.showErrorWithStatus("微博长度超过限制")
            return
        }
        
        SVProgressHUD.showWithStatus("正在发送...")
        
        CZNetworkTool.sharedInstance.sendStatus(text,image: image) { (result, error) -> () in
            if error != nil {
            
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
            //延迟
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })

        }
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareUI()
        
        //管理起来
        self.addChildViewController(photoSelectorVC)
        self.addChildViewController(emotionVC)
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)

    }
    
    
    //在用户可以控件时候跳出键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if photoSelectorViewBottomCon?.constant != 0 {
            //弹出键盘
            textView.becomeFirstResponder()
        }
    }
    
    
    //移除通知
    deinit {
      NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    
    // 键盘frame将要改变时的通知方法
    func willChangeFrame(notification: NSNotification) {
//        print("notification: \(notification)")
        // 获取动画时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        // 获取键盘的最终位置
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 改变toolBar底部的约束
        toolBarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    func prepareUI() {
    
        //背景颜色
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        setupTextView()
        
        setupPhoto()
        setupToolBar()
        
        //设置剩余
         setupTipLengthLabel()
     

    }
    
    
    ///设置照片选择器
    func setupPhoto() {
    
        let photoSelectorView = photoSelectorVC.view
        //添加控件
        view.addSubview(photoSelectorView)
        
        //添加约束
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        
       view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["psv" : photoSelectorView]))

        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: view.frame.height * 0.6))
        //底部
        photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6)
        view.addConstraint(photoSelectorViewBottomCon!)
        
    }
    
    
    //设置剩余文字
    func  setupTipLengthLabel() {
        
       view.addSubview(tipLengthLabel)
        
        //添加约束
        tipLengthLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -5, y: -5))
        
    }
    
    
    func setupNav() {
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
         setupTitleView()
    }
    
    func setupTitleView(){
        
        let prefix = "发微博"
        if let name = CZUserAccount.userAccount?.screen_name {
        let text = prefix + "\n" + name
          //创建label
            let label = UILabel()
            label.numberOfLines = 0
            label.textColor = UIColor.blackColor()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
//            label.text = text
           
          
            //设置属性颜色的大学
            let attrText = NSMutableAttributedString(string: text)
            let nameRange = (text as NSString).rangeOfString(name)
            
            attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            attrText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: nameRange)
            
            
            label.attributedText = attrText
             label.sizeToFit()
              navigationItem.titleView = label
            
        }else {
        navigationItem.title = prefix
        }
    }

    //设置工具条
    private func setupToolBar() {
    
        //添加控件
        view.addSubview(toolBar)
        //添加约束
       let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        //取出toolbar顶部约束
        toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        
        let itemSettings = [["imageName": "compose_toolbar_picture","action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "mention"],
            ["imageName": "compose_mentionbutton_background","action": "trend"],
            ["imageName": "compose_emoticonbutton_background","action": "emoticon"],
            ["imageName": "compose_addbutton_background","action": "add"]]
    
        var items = [UIBarButtonItem]()
        
        
        
            for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            let item = UIBarButtonItem(imageName: imageName)
                
            let button = item.customView as? UIButton
            button?.addTarget(self, action:Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            items.append(item)
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
             items.append(flexibleSpace)
           
        }
        
        items.removeLast()
        toolBar.items = items
    }
    
    func setupTextView() {
    
        textView.delegate = self
        
        view.addSubview(textView)
        
        textView.ff_Fill(view)
    }
    
    //MARK: - 点击事件
    func picture() {
        //让照片选择权到view
        photoSelectorViewBottomCon?.constant = 0
        //退下
        textView.resignFirstResponder()
        
        //动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func mention() {
        print("#")
    }
    func trend() {
        print("@")
    }
    ///切换键盘
    func emoticon() {
        print("textView.inputView: \(textView.inputView)")
         // 将键盘退回,如果退出键盘和弹出键盘事件相差很短,不会有退回去和弹出来的动画
        textView.resignFirstResponder()
        
        //延时0.25秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 如果使用的是系统键盘,就切换到我们的键盘,如果使用的是我们的键盘就切换到系统
            self.textView.inputView = self.textView.inputView == nil ? self.emotionVC.view : nil
            //再次弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    func add() {
        print("加号")
    }
    
    
    private lazy var textView: SCPlaceholderTextView = {
        let textView = SCPlaceholderTextView()
        textView.backgroundColor = UIColor.brownColor()
        textView.font = UIFont.systemFontOfSize(18)
        textView.alwaysBounceVertical = true
        textView.placeholderText = "分享新鲜事..."
        
        return textView
    }()
    
    ///表情键盘控制器
    private lazy var emotionVC: SCEmoticonViewController = SCEmoticonViewController(textView: self.textView)
    
    ///照片选择器控制器
    private lazy var photoSelectorVC: SCPhotoSelectorViewController = SCPhotoSelectorViewController()
    
    
    
    //MARK: - 懒加载
    private lazy var toolBar: UIToolbar = {
        let tool = UIToolbar()
        tool.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return tool
    }()
    
    ///剩余文字label
    private lazy var tipLengthLabel: UILabel = {
         let label = UILabel()
        //字体大小
        label.font = UIFont.systemFontOfSize(13)
        label.textColor = UIColor.whiteColor()
        
        return label
    }()
    
    
}

//扩展代理方法
extension CZSendStatusController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView)
    {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
         // 获取textView现有的文字数量
        let count = textView.emoticonText().characters.count
        
        let length = maxTipLength - count
        
        //设置剩余文字
        tipLengthLabel.text = String(length)
        
        //设置颜色
        tipLengthLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}

